package NG::Sys::Cache::Memcached;
use strict;
use warnings;
use utf8;

use base 'NG::Sys::Cache::Base';

my $cache;

sub create_cache {
	my ($self) = @_;
	my $filename;
	
	unless($cache){
        $cache = $self->_create_cache;
	}
	$self->{cache} = $cache;
}


sub _create_cache {
	my ($self) = @_;
	require NG::Sys::App;
	require Cache::Memcached::Fast;
	my $obj = Cache::Memcached::Fast->new({
				servers => NG::Sys::App::app()->{cfg}{srv}{memcached},
				});
	return $obj;
}

sub incr {
	my ($self,$key,$by) = @_;
	$by ||= 1;
	return $self->{cache}->inrc($self->{prefix}.$key,$by);
}
sub decr {
	my ($self,$key,$by) = @_;
	$by ||= 1;
	return $self->{cache}->decr($self->{prefix}.$key,$by);
}
sub try_lock {
	my ($self,$key) = @_;
	unless($self->{cache}->add($self->{prefix}.$key,time())){
		return $self->{cache}->get($self->{prefix}.$key);
	}else{
		return undef;
	}
}
sub free_lock {
	my ($self,$key) = @_;
	$self->{cache}->remove($self->{prefix}.$key);
}

1;

